<template>
    <div class="my-activities">
        <div class="registered-activities">
            <div class="filter-container">
                <el-input v-model="registeredQuery.title" placeholder="搜索活动标题" style="width: 200px;" class="filter-item"
                    @keyup.enter.native="getRegisteredList" />
                <el-select v-model="registeredQuery.activityType" placeholder="活动类型" clearable style="width: 120px"
                    class="filter-item">
                    <el-option label="讲座" :value="1" />
                    <el-option label="赛事" :value="2" />
                    <el-option label="培训" :value="3" />
                </el-select>
                <el-select v-model="registeredQuery.status" placeholder="活动状态" clearable style="width: 120px"
                    class="filter-item">
                    <el-option label="报名中" :value="0" />
                    <el-option label="进行中" :value="1" />
                    <el-option label="已结束" :value="2" />
                </el-select>
                <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getRegisteredList">
                    搜索
                </el-button>
                <el-button class="filter-item" type="default" @click="handleResetRegistered">
                    重置
                </el-button>
            </div>

            <el-table v-loading="registeredLoading" :data="registeredList" border fit highlight-current-row>
                <el-table-column align="center" label="ID" width="60">
                    <template slot-scope="scope">
                        {{ scope.row.id }}
                    </template>
                </el-table-column>
                <el-table-column label="活动标题" min-width="200" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <router-link :to="'/activity/detail/' + scope.row.id" class="link-type">
                            <el-tooltip :content="scope.row.title" placement="top"
                                :disabled="scope.row.title.length <= 20">
                                <span class="title-text">{{ scope.row.title }}</span>
                            </el-tooltip>
                        </router-link>
                    </template>
                </el-table-column>
                <el-table-column label="类型" width="70" align="center">
                    <template slot-scope="scope">
                        <el-tag :type="getTypeTagType(scope.row.activityType)" size="small">
                            {{ getTypeLabel(scope.row.activityType) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="发布者" width="90" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.publishName }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="开始时间" width="160" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.startTime }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="结束时间" width="160" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.endTime }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="报名截止" width="160" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.registrationDeadline }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="附件" width="100" align="center">
                    <template slot-scope="scope">
                        <div v-if="scope.row.attachments && scope.row.attachments.length > 0">
                            <el-dropdown @command="handleDownloadAttachment" trigger="click">
                                <el-button type="text" size="mini" class="attachment-btn">
                                    <i class="el-icon-paperclip"></i>
                                    附件({{ scope.row.attachments.length }})
                                </el-button>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item v-for="(file, index) in scope.row.attachments" :key="index"
                                        :command="{ file, activity: scope.row }" class="attachment-item">
                                        <i :class="getFileIcon(file.name)" class="file-icon"></i>
                                        <span class="file-name">{{ file.name }}</span>
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>
                        </div>
                        <span v-else class="no-attachment">无附件</span>
                    </template>
                </el-table-column>
                <el-table-column label="状态" width="70" align="center">
                    <template slot-scope="scope">
                        <el-tag :type="getStatusTagType(scope.row.status)" size="small">
                            {{ getStatusLabel(scope.row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="报名状态" width="90" align="center">
                    <template slot-scope="scope">
                        <el-tag :type="getRegistrationStatusTagType(scope.row)" size="small">
                            {{ getRegistrationStatusLabel(scope.row) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="已报名/限制人数" width="120" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.currentParticipants }}/{{ scope.row.maxParticipants || '∞' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="签到状态" width="90" align="center">
                    <template slot-scope="scope">
                        <el-tag :type="getAttendanceStatusTagType(scope.row.attendanceStatus)" size="small">
                            {{ getAttendanceStatusLabel(scope.row.attendanceStatus) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="签到时间" width="160" align="center">
                    <template slot-scope="scope">
                        <span v-if="scope.row.attendanceTime">{{ scope.row.attendanceTime }}</span>
                        <span v-else class="text-muted">未签到</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" align="center" width="280">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="handleView(scope.row)">
                            查看详情
                        </el-button>
                        <el-button v-if="canCheckIn(scope.row)" type="warning" size="mini"
                            @click="handleCheckIn(scope.row)">
                            签到
                        </el-button>
                        <el-button v-if="canDownloadCertificate(scope.row)" type="success" size="mini"
                            @click="handleDownloadCertificate(scope.row)">
                            下载证明
                        </el-button>
                        <el-button v-if="canCancel(scope.row)" type="danger" size="mini"
                            @click="handleCancel(scope.row)">
                            取消报名
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="registeredTotal > 0" :total="registeredTotal" :page.sync="registeredQuery.pageNo"
                :limit.sync="registeredQuery.pageSize" @pagination="getRegisteredList" />
        </div>
    </div>
</template>

<script>
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import { getStudentList, cancelRegisterActivity, checkInActivity } from '@/api/activity'
export default {
    name: 'MyActivities',
    components: { Pagination },
    filters: {
        parseTime
    },
    data() {
        return {
            // 已报名活动
            registeredList: [],
            registeredTotal: 0,
            registeredLoading: true,
            registeredQuery: {
                pageNo: 1,
                pageSize: 20,
                title: undefined,
                activityType: undefined,
                status: undefined
            }
        }
    },
    created() {
        this.getRegisteredList()
    },
    methods: {
        async getRegisteredList() {
            this.registeredLoading = true
            try {
                // 确保分页参数不为空
                const queryParams = {
                    ...this.registeredQuery,
                    pageNo: this.registeredQuery.pageNo || 1,
                    pageSize: this.registeredQuery.pageSize || 20
                }

                console.log('发送查询参数:', queryParams)

                const res = await getStudentList(queryParams)
                this.registeredList = res.data.records || [];
                this.registeredTotal = res.data.total || 0;
                res.data.records.forEach(item => {
                    item.attachments = JSON.parse(item.attachmentUrl || '[]')
                })
            } catch (error) {
                console.error('获取学生活动列表失败:', error)
                this.$message.error('获取活动列表失败，请重试')
            } finally {
                this.registeredLoading = false
            }
        },
        handleResetRegistered() {
            this.registeredQuery = {
                pageNo: 1,
                pageSize: 20,
                title: undefined,
                activityType: undefined,
                status: undefined
            }
            this.getRegisteredList()
        },
        handleView(row) {
            this.$router.push(`/activity/detail/${row.id}`)
        },
        async handleCancel(row) {
            try {
                await this.$confirm(`确认取消报名"${row.title}"活动？`, '取消报名确认', {
                    confirmButtonText: '确定取消',
                    cancelButtonText: '我再想想',
                    type: 'warning'
                })

                // 调用取消报名API
                await cancelRegisterActivity(row.id)

                this.$message({
                    type: 'success',
                    message: '取消报名成功！'
                })

                // 刷新列表
                this.getRegisteredList()
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('取消报名失败:', error)
                    this.$message({
                        type: 'error',
                        message: '取消报名失败，请重试'
                    })
                }
            }
        },
        handleDownloadCertificate(row) {
            try {
                if (!row.certificateUrl) {
                    this.$message({
                        type: 'warning',
                        message: '证明文件不存在'
                    })
                    return
                }

                // 创建下载链接
                const link = document.createElement('a')
                link.href = row.certificateUrl
                link.download = `${row.title}_参与证明.pdf`
                link.target = '_blank'
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)

                this.$message({
                    type: 'success',
                    message: '证明下载成功！'
                })
            } catch (error) {
                console.error('下载证明失败:', error)
                this.$message({
                    type: 'error',
                    message: '下载证明失败，请重试'
                })
            }
        },
        canCancel(row) {
            // 判断是否可以取消报名的条件：
            // 1. 活动状态为发布状态 (status === 1)
            // 2. 当前时间 < 活动开始时间
            // 3. 用户已经报名 (isAnticipate === 1)

            if (row.status !== 1 || row.isAnticipate !== 1) {
                return false
            }

            const now = new Date()
            const startTime = new Date(row.startTime)

            // 活动还未开始才能取消报名
            return now < startTime
        },
        canDownloadCertificate(row) {
            // 判断是否可以下载证明的条件：
            // 1. 用户已经报名 (isAnticipate === 1)
            // 2. 有证明链接 (certificateUrl 不为空)

            return row.isAnticipate === 1 && row.certificateUrl && row.certificateUrl.trim() !== ''
        },
        canCheckIn(row) {
            // 判断是否可以签到的条件：
            // 1. 用户已经报名 (isAnticipate === 1)
            // 2. 活动已经开始 (当前时间 >= 开始时间)
            // 3. 活动还未结束 (当前时间 <= 结束时间)
            // 4. 还未签到 (attendanceStatus === 0)
            // 5. 活动状态为发布状态 (status === 1)

            if (row.isAnticipate !== 1 || row.status !== 1 || row.attendanceStatus !== 0) {
                return false
            }

            const now = new Date()
            const startTime = new Date(row.startTime)
            const endTime = new Date(row.endTime)

            // 活动进行中才能签到
            return now >= startTime && now <= endTime
        },
        async handleCheckIn(row) {
            try {
                await this.$confirm(`确认签到参加"${row.title}"活动？`, '签到确认', {
                    confirmButtonText: '确认签到',
                    cancelButtonText: '取消',
                    type: 'info'
                })

                // 调用签到API
                await checkInActivity(row.id)

                this.$message({
                    type: 'success',
                    message: '签到成功！'
                })

                // 刷新列表
                this.getRegisteredList()
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('签到失败:', error)
                    this.$message({
                        type: 'error',
                        message: '签到失败，请重试'
                    })
                }
            }
        },
        getAttendanceStatusLabel(status) {
            const statusMap = {
                0: '未签到',
                1: '已签到'
            }
            return statusMap[status] || '未知'
        },
        getAttendanceStatusTagType(status) {
            const statusMap = {
                0: 'info',      // 未签到 - 灰色
                1: 'success'    // 已签到 - 绿色
            }
            return statusMap[status] || ''
        },
        handleDownloadAttachment(command) {
            const { file, activity } = command
            // 创建下载链接
            const link = document.createElement('a')
            link.href = file.url
            link.download = file.name
            link.target = '_blank'
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)

            this.$message.success(`开始下载：${file.name}`)
        },
        getFileIcon(fileName) {
            const ext = fileName.split('.').pop().toLowerCase()
            const iconMap = {
                pdf: 'el-icon-document',
                doc: 'el-icon-document',
                docx: 'el-icon-document',
                xls: 'el-icon-s-grid',
                xlsx: 'el-icon-s-grid',
                ppt: 'el-icon-picture-outline',
                pptx: 'el-icon-picture-outline',
                txt: 'el-icon-document-copy',
                zip: 'el-icon-folder-opened',
                rar: 'el-icon-folder-opened'
            }
            return iconMap[ext] || 'el-icon-document'
        },
        getTypeLabel(type) {
            const typeMap = {
                // 字符串类型（兼容旧数据）
                lecture: '讲座',
                competition: '赛事',
                training: '培训',
                // 数字类型（新数据）
                1: '讲座',
                2: '赛事',
                3: '培训'
            }
            return typeMap[type] || type
        },
        getTypeTagType(type) {
            const typeMap = {
                // 字符串类型（兼容旧数据）
                lecture: 'primary',
                competition: 'success',
                training: 'warning',
                // 数字类型（新数据）
                1: 'primary',
                2: 'success',
                3: 'warning'
            }
            return typeMap[type] || ''
        },
        getStatusLabel(status) {
            const statusMap = {
                // 时间判断状态（筛选用）
                0: '报名中',
                1: '进行中',
                2: '已结束',
                // 活动发布状态（显示用）
                3: '取消',
                // 兼容字符串格式
                registering: '报名中',
                ongoing: '进行中',
                finished: '已结束'
            }
            return statusMap[status] || status;
        },
        getStatusTagType(status) {
            const statusMap = {
                // 时间判断状态（筛选用）
                0: 'success',    // 报名中 - 绿色
                1: 'warning',    // 进行中 - 橙色
                2: 'info',       // 已结束 - 灰色
                // 活动发布状态（显示用）
                3: 'danger',     // 取消 - 红色
                // 兼容字符串格式
                registering: 'success',
                ongoing: 'warning',
                finished: 'info'
            }
            return statusMap[status] || ''
        },
        // 获取报名状态标签文本
        getRegistrationStatusLabel(row) {
            const now = new Date()
            const registrationDeadline = new Date(row.registrationDeadline)
            const startTime = new Date(row.startTime)
            const endTime = new Date(row.endTime)

            // 如果活动状态不是发布状态，直接返回对应状态
            if (row.status !== 1) {
                return this.getStatusLabel(row.status)
            }

            // 活动已结束
            if (now > endTime) {
                return '已结束'
            }

            // 活动进行中
            if (now >= startTime && now <= endTime) {
                return '进行中'
            }

            // 报名已截止但活动未开始
            if (now > registrationDeadline && now < startTime) {
                return '报名截止'
            }

            // 报名中
            if (now <= registrationDeadline) {
                // 检查是否已满员
                if (row.maxParticipants && row.currentParticipants >= row.maxParticipants) {
                    return '已满员'
                }
                return '报名中'
            }

            return '未知'
        },
        // 获取报名状态标签类型
        getRegistrationStatusTagType(row) {
            const now = new Date()
            const registrationDeadline = new Date(row.registrationDeadline)
            const startTime = new Date(row.startTime)
            const endTime = new Date(row.endTime)

            // 如果活动状态不是发布状态
            if (row.status !== 1) {
                return this.getStatusTagType(row.status)
            }

            // 活动已结束
            if (now > endTime) {
                return 'info'
            }

            // 活动进行中
            if (now >= startTime && now <= endTime) {
                return 'success'
            }

            // 报名已截止但活动未开始
            if (now > registrationDeadline && now < startTime) {
                return 'warning'
            }

            // 报名中
            if (now <= registrationDeadline) {
                // 检查是否已满员
                if (row.maxParticipants && row.currentParticipants >= row.maxParticipants) {
                    return 'danger'
                }
                return 'primary'
            }

            return ''
        },
        getActivityStatusLabel(status) {
            const statusMap = {
                upcoming: '未开始',
                ongoing: '进行中',
                finished: '已结束'
            }
            return statusMap[status] || status
        },
        getActivityStatusTagType(status) {
            const statusMap = {
                upcoming: 'warning',
                ongoing: 'success',
                finished: 'info'
            }
            return statusMap[status] || ''
        }
    }
}
</script>

<style lang="scss" scoped>
.my-activities {
    padding: 20px;
}

.filter-container {
    padding-bottom: 10px;

    .filter-item {
        display: inline-block;
        vertical-align: middle;
        margin-bottom: 10px;
        margin-right: 10px;
    }
}

.link-type {
    color: #409EFF;
    text-decoration: none;
    display: block;

    &:hover {
        color: #66b1ff;
    }

    .title-text {
        display: inline-block;
        max-width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        vertical-align: top;
    }
}

.certificates-container {
    margin-top: 20px;
}

.no-attachment {
    color: #c0c4cc;
    font-size: 12px;
}

::v-deep .el-dropdown {
    .el-button--text {
        color: #409EFF;

        &:hover {
            color: #66b1ff;
        }
    }
}

::v-deep .el-dropdown-menu__item {
    padding: 8px 16px;

    i {
        margin-right: 8px;
        color: #409EFF;
    }

    &:hover {
        background-color: #ecf5ff;
        color: #409EFF;
    }
}

.text-muted {
    color: #909399;
    font-style: italic;
}
</style>
